<template>
  <div>
    <MyHeader @addTodo="addTodo"/>
    <MyList :todos="todos"/>
    <MyFooter :todos="todos" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"/>


  </div>

</template>

<script>
//引入组件
import MyHeader from "./components/MyHeader.vue";
import MyList from "./components/MyList.vue";
import MyFooter from "./components/MyFooter.vue";
import pubSub from "pubsub-js";
export default {
  name: 'App',
  components: {
    MyHeader: MyHeader,
    MyList: MyList,
    MyFooter: MyFooter,
  },
  data: function () {
    return {
      todos: JSON.parse(window.localStorage.getItem('todos')) || []
    }
  },
  methods: {
    addTodo: function (todoObj) {
      this.todos.unshift(todoObj);
    },
    checkTodo: function (id) {
      this.todos.forEach((todo) => {
        if (todo.id === id) {
          todo.done = !todo.done
        }
      })
    },
    deleteTodo: function (_,id) {

      this.todos = this.todos.filter((todo) => {
        return todo.id !== id;
      })
    },
    checkAllTodo: function (done) {
      this.todos.forEach((todo) => {
        todo.done = done;
      })
    },
    clearAllTodo: function () {
      //filter方法不会修改原始数组，重新赋值一下
      this.todos = this.todos.filter(todo => {
        //done值为真的不需要--- 意思就是说过滤出来done为false的值
        return !todo.done
      })
    }
  },
  watch: {
    todos: {
      deep: true,
      handler: function (nv) {
        window.localStorage.setItem('todos', JSON.stringify(nv))
      }
    }
  },
  mounted() {
    this.$bus.$on('checkTodo',this.checkTodo)
    // this.$bus.$on('deleteTodo',this.deleteTodo)
    this.pubID = pubSub.subscribe('deleteTodo',this.deleteTodo)
  },
  beforeDestroy() {
    this.$bus.$off('checkTodo')
    pubSub.unsubscribe(this.pubID)

  }


}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
